package zhengyanze.com.aipoemmax.guide.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import zhengyanze.com.aipoemmax.R;
import zhengyanze.com.aipoemmax.guide.Constant;
import zhengyanze.com.aipoemmax.guide.activity.base.BaseActivity;
import zhengyanze.com.aipoemmax.guide.adapter.MainAdapter;
import zhengyanze.com.aipoemmax.guide.bean.PoemBean;
import zhengyanze.com.aipoemmax.guide.login.LoginActivity;

public class MainActivity extends BaseActivity {
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.rv_main)
    RecyclerView rvMain;
    @BindView(R.id.refreshLayout)
    RefreshLayout refreshLayout;
    @BindView(R.id.dl)
    DrawerLayout dl;

    ArrayList<PoemBean> mPoemBeans;
    @BindView(R.id.iv_header)
    ImageView ivHeader;
    @BindView(R.id.bt_login)
    Button btLogin;

    private MainAdapter mainAdapter;

    public static final int RESULT_CODE = 111;

    int index = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        mPoemBeans = new ArrayList<>();
        initView();

        initData(true, Constant.URL.GUSHIWEN);
    }

    //第二次启动
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        btLogin.setEnabled(false);
        btLogin.setText("已登录");
    }

    public void initView() {
        setSupportActionBar(toolbar);
        setTitle("最美古诗词");
        toolbar.setNavigationIcon(R.mipmap.bar_drawer_menu_normal);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dl.openDrawer(Gravity.START);
            }
        });

        rvMain.setLayoutManager(new LinearLayoutManager(this));
        mainAdapter = new MainAdapter(mPoemBeans);
        rvMain.setAdapter(mainAdapter);

        /**
         * 上拉刷新,下拉加载监听
         */
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.finishRefresh(2000);
                initData(true, Constant.URL.GUSHIWEN);
                index = 1;
            }
        });
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
//                Toast.makeText(MainActivity.this, "加载更多", Toast.LENGTH_SHORT).show();
                refreshlayout.finishLoadmore(2000);
                index++;
                String moreUri = Constant.URL.GUSHIWEN + "default_" + index + ".aspx";
                initData(false, moreUri);
            }
        });
    }


    /**
     * 获取网络数据
     */
    public void initData(final boolean isResh, final String url) {
//        DialogManager.showDialog(this, "加载中...");
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Document document = Jsoup.connect(url).get();
                    Element main3 = document.getElementsByClass("main3").first();
                    Element left = main3.getElementsByClass("left").first();

                    Elements sons = left.getElementsByClass("sons");
                    ArrayList<PoemBean> tempArray = new ArrayList<PoemBean>();
                    for (Element em : sons) {
                        Element cont = em.getElementsByClass("cont").first();
                        Element a = cont.after("a");

                        Elements p = a.getElementsByTag("p");
                        String title = p.text().split(" ")[0];
//                            System.out.println("标题是:" + title);
                        String author = p.text().split(" ")[1];
//                            System.out.println("作者是:" + author);

                        Element txt = p.first().after("a");
                        String link = txt.getElementsByTag("a").attr("href");
//                            System.out.println("标题超链接是 : " + link);

                        Element con = a.getElementsByClass("contson").first();
                        String content = con.text();
//                            System.out.println("内容是 : " + content);

                        PoemBean bean = new PoemBean(title, author, content, link);
                        tempArray.add(bean);
                    }
                    if (isResh) {
                        refush(tempArray);
                    } else {
                        loadMore(tempArray);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 刷新
     */
    private void refush(ArrayList<PoemBean> tempArray) {
        mPoemBeans.clear();
        mPoemBeans.addAll(tempArray);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
//                DialogManager.dismissDialog();
                mainAdapter.notifyDataSetChanged();
            }
        });
    }

    /**
     * 加载更多
     */
    private void loadMore(ArrayList<PoemBean> tempArray) {
        mPoemBeans.addAll(tempArray);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
//                DialogManager.dismissDialog();
                mainAdapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 菜单
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.setting:
//                Toast.makeText(this, "设置", Toast.LENGTH_SHORT).show();
                startActivity(new Intent(this,Setting.class));
                break;
            case R.id.sou:
                startActivity(new Intent(this, SearchActivity.class));
                overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
                break;
        }
        return true;
    }

    @OnClick({R.id.btn_shaix, R.id.bt_login, R.id.ll_mycollect, R.id.ll_mymessage,R.id.ll_suibi})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_shaix:
                //筛选
                startActivityForResult(new Intent(this, FilterActivity.class), RESULT_CODE);
                overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
                break;
            case R.id.bt_login:
                //登录
//                startActivity(new Intent(this, LoginActivity.class));
                break;
            case R.id.ll_mycollect:
                startActivity(new Intent(this,LocationCollectActivity.class));
                break;
            case R.id.ll_suibi:
                startActivity(new Intent(this,SuiBiActicity.class));
                break;
        }
    }
}
